package com.yj.auto.core.web.system.service;

import java.util.List;

import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.SqlPara;
import com.yj.auto.Constants;
import com.yj.auto.core.base.annotation.Service;
import com.yj.auto.core.base.model.QueryModel;
import com.yj.auto.core.jfinal.base.BaseCache;
import com.yj.auto.core.jfinal.base.BaseService;
import com.yj.auto.core.web.system.model.Area;
import com.yj.auto.core.web.system.model.Resource;

/**
 * Area 管理 描述：
 */
@Service(name = "areaSrv")
public class AreaService extends BaseService<Area> implements BaseCache {

	private static final Log logger = Log.getLog(AreaService.class);

	public static final String SQL_LIST = "system.area.list";

	public static final Area dao = new Area().dao();

	@Override
	public Area getDao() {
		return dao;
	}

	@Override
	public SqlPara getListSqlPara(QueryModel query) {
		if (StrKit.isBlank(query.getOrderby())) {
			query.setOrderby("sort");
		}
		return getSqlPara(SQL_LIST, query);
	}

	// 根据区域编码查询
	public Area getByCode(String code) {
		String sql = "select * from t_sys_area where code=?";
		return dao.findFirst(sql, code);
	}

	public boolean save(Area model) {
		boolean success = model.save();
		if (success) {
			updatePath(model);
		}
		return success;
	}

	public boolean update(Area model) {
		boolean success = model.update();
		if (success) {
			updatePath(model);
		}
		return success;
	}

	private void updatePath(Area model) {
		Area temp = model;
		String path = "," + model.getId() + ",";
		String full = model.getName();
		while (temp.getParentId() != 0) {
			Area parent = this.get(temp.getParentId());
			if (null == parent) {
				break;
			} else {
				path = "," + parent.getId() + path;
				full = parent.getName() + "-" + full;
			}
			temp = parent;
		}
		model.setPath(path);
		model.setFullname(full);
		model.update();
	}

	public List<Area> children(Integer id, String state) {
		if (null == id)
			id = new Integer(1);
		QueryModel query = new QueryModel();
		query.setId(id);
		query.setState(state);
		query.setOrderby("sort");
		return find(SQL_LIST, query);
	}

	@Override
	public void loadCache() {
		QueryModel query = new QueryModel();
		query.setId(0);//缓存太多,先只缓存第一级
		query.setOrderby("sort");
		query.setState(Constants.DATA_STATE_VALID);
		List<Area> list = find(SQL_LIST, query);
		for (Area r : list) {
			addCache(r.getId(), r);
		}
	}

	@Override
	public String getCacheName() {
		return Constants.CACHE_NAME_AREA;
	}
}